package com.emperor.course.app;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;

import com.emperor.category.logic.Category;
import com.emperor.category.logic.CategoryModel;
import com.emperor.core.app.App;
import com.emperor.core.app.AppBase;
import com.emperor.core.app.AppConstant;
import com.emperor.course.logic.Course;
import com.emperor.course.logic.CourseModel;
import com.emperor.course.logic.CourseProduct;
import com.emperor.course.logic.CourseProductModel;
import com.emperor.course.logic.CourseTreatment;
import com.emperor.course.logic.CourseTreatmentModel;
import com.emperor.inventory.app.InventoryAppCtrl;
import com.emperor.inventory.app.InventoryAppEnq;
import com.emperor.product.logic.Product;
import com.emperor.treatment.logic.Treatment;
import com.emperor.util.HibernateUtil;
import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Group;

public class CourseAppMgm extends AppBase implements App {

	private Label categoryLabel_3_4;
	private Text text_12;
	private Button resetButton;
	private Button updateButton;
	private Combo combo_2;
	private Text text_9;
	private Text text_8;
	private Text text_7;
	private Combo combo;
	private Text text_6;
	private Text text_5;
	private Text text_4;
	private Text text_3;
	private Text text_2;
	private Text text;
	protected Shell shlUpdateCourse;

	public static Logger log = Logger.getLogger(CourseAppMgm.class);
	private Table table;
	private Table tableTreatment;

	public CourseAppMgm() {
		super();
	}

	public CourseAppMgm(Map<String, Object> params) {
		super();
		this.params = params;
	}

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			CourseAppMgm window = new CourseAppMgm();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window
	 */
	public void open() {
		final Display display = Display.getDefault();
		createContents();
		shlUpdateCourse.open();
		shlUpdateCourse.layout();
		while (!shlUpdateCourse.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {
		shlUpdateCourse = new Shell();
		shlUpdateCourse.setBackgroundImage(SWTResourceManager.getImage(
				CourseAppMgm.class, "/img/main.jpg"));
		shlUpdateCourse.setImage(SWTResourceManager.getImage(
				CourseAppMgm.class, "/img/iMac OSX.png"));
		shlUpdateCourse.setBackgroundMode(SWT.INHERIT_DEFAULT);
		shlUpdateCourse.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		shlUpdateCourse.setSize(1280, 800);
		shlUpdateCourse.setText("Update Course");

		initScreen(shlUpdateCourse, getParams());

		final Composite composite = new Composite(shlUpdateCourse, SWT.NONE);
		composite.setBounds(0, 50, 1272, 661);

		final Label messageLabel = new Label(composite, SWT.NONE);
		messageLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		messageLabel
				.setText("Please update the Course Detail and click Update button to save the changes.");
		messageLabel.setBounds(10, 10, 578, 20);

		text = new Text(composite, SWT.BORDER);
		text.setToolTipText("course_name");
		text.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI",
				12, SWT.NORMAL));
		text.setBounds(185, 70, 403, 30);

		text_2 = new Text(composite, SWT.BORDER);
		text_2.setToolTipText("course_sku");
		text_2.setBounds(185, 106, 403, 30);
		text_2.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));

		text_3 = new Text(composite, SWT.BORDER);
		text_3.setToolTipText("course_price");
		text_3.setBounds(778, 70, 203, 30);
		text_3.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));

		text_4 = new Text(composite, SWT.BORDER);
		text_4.setToolTipText("course_discount");
		text_4.setBounds(778, 106, 203, 30);
		text_4.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));

		text_5 = new Text(composite, SWT.BORDER);
		text_5.setToolTipText("course_quantity");
		text_5.setBounds(185, 142, 203, 30);
		text_5.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));

		text_6 = new Text(composite, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER);
		text_6.setToolTipText("course_desc");
		text_6.setBounds(778, 142, 403, 76);
		text_6.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));

		combo = new Combo(composite, SWT.NONE);
		combo.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI",
				12, SWT.NORMAL));
		combo.setBounds(185, 36, 403, 28);

		text_7 = new Text(composite, SWT.BORDER);
		text_7.setVisible(false);
		text_7.setBounds(779, 188, 203, 30);
		text_7.setToolTipText("prod_id");
		text_7.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));

		text_8 = new Text(composite, SWT.BORDER);
		text_8.setVisible(false);
		text_8.setBounds(779, 224, 203, 30);
		text_8.setToolTipText("prod_status");
		text_8.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));

		final Label categoryLabel = new Label(composite, SWT.NONE);
		categoryLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		categoryLabel.setText("Category");
		categoryLabel.setBounds(10, 39, 65, 20);

		final Label categoryLabel_1 = new Label(composite, SWT.NONE);
		categoryLabel_1.setBounds(10, 73, 65, 20);
		categoryLabel_1.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		categoryLabel_1.setText("Name");

		final Label categoryLabel_2 = new Label(composite, SWT.NONE);
		categoryLabel_2.setBounds(10, 109, 65, 20);
		categoryLabel_2.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		categoryLabel_2.setText("SKU");

		final Label categoryLabel_3 = new Label(composite, SWT.NONE);
		categoryLabel_3.setBounds(603, 73, 65, 20);
		categoryLabel_3.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		categoryLabel_3.setText("Price");

		final Label categoryLabel_4 = new Label(composite, SWT.NONE);
		categoryLabel_4.setBounds(603, 109, 65, 20);
		categoryLabel_4.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		categoryLabel_4.setText("Discount");

		final Label categoryLabel_5 = new Label(composite, SWT.NONE);
		categoryLabel_5.setBounds(10, 145, 65, 20);
		categoryLabel_5.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		categoryLabel_5.setText("Quantity");

		final Label categoryLabel_6 = new Label(composite, SWT.NONE);
		categoryLabel_6.setBounds(603, 145, 80, 20);
		categoryLabel_6.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		categoryLabel_6.setText("Description");
		final Label categoryLabel_3_1 = new Label(composite, SWT.NONE);
		categoryLabel_3_1.setVisible(false);
		categoryLabel_3_1.setBounds(603, 283, 65, 20);
		categoryLabel_3_1.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		categoryLabel_3_1.setText("Weight");

		text_9 = new Text(composite, SWT.BORDER);
		text_9.setVisible(false);
		text_9.setBounds(778, 280, 203, 30);
		text_9.setToolTipText("prod_weight");
		text_9.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));

		text_12 = new Text(composite, SWT.BORDER);
		text_12.setBounds(778, 34, 203, 30);
		text_12.setToolTipText("course_cost");
		text_12.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));

		categoryLabel_3_4 = new Label(composite, SWT.NONE);
		categoryLabel_3_4.setBounds(603, 37, 65, 20);
		categoryLabel_3_4.setFont(org.eclipse.wb.swt.SWTResourceManager
				.getFont("Segoe UI", 12, SWT.NORMAL));
		categoryLabel_3_4.setText("Cost");
		//
		populateControls(composite, combo);

		table = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION);
		table.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI",
				12, SWT.NORMAL));
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				TableItem[] items = table.getSelection();
				if (items != null && items.length > 0) {
					for (int i = 0; i < items.length; i++) {
						TableItem item = items[i];
						if (item.getData() != null) {
							CourseProduct courseProduct = (CourseProduct) item
									.getData();

							getParams().put(CourseAppCtrl.COURSEPROD_ID,
									courseProduct.getId());
							getParams().put(CourseAppCtrl.COURSE_ID,
									courseProduct.getCourse().getId());

							CourseProdAppMgm dialog = new CourseProdAppMgm(
									getShell(), SWT.ICON_INFORMATION,
									getParams());
							dialog.open();
						}
					}
				}
			}
		});
		table.setBounds(10, 242, 1171, 145);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		TableColumn tblclmnNo = new TableColumn(table, SWT.NONE);
		tblclmnNo.setWidth(100);
		tblclmnNo.setText("No.");

		TableColumn tblclmnName = new TableColumn(table, SWT.NONE);
		tblclmnName.setWidth(507);
		tblclmnName.setText("Name");

		TableColumn tblclmnSku = new TableColumn(table, SWT.NONE);
		tblclmnSku.setWidth(314);
		tblclmnSku.setText("SKU");

		TableColumn tblclmnPrice = new TableColumn(table, SWT.NONE);
		tblclmnPrice.setWidth(100);
		tblclmnPrice.setText("Price");

		TableColumn tblclmnQuantity = new TableColumn(table, SWT.NONE);
		tblclmnQuantity.setWidth(142);
		tblclmnQuantity.setText("Quantity");

		final Label lblProducts = new Label(composite, SWT.NONE);
		lblProducts.setText("Product(s)");
		lblProducts.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		lblProducts.setBounds(10, 211, 605, 20);

		final Label lblTreatments = new Label(composite, SWT.NONE);
		lblTreatments.setText("Treatment(s)");
		lblTreatments.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		lblTreatments.setBounds(10, 408, 605, 20);

		resetButton = new Button(composite, SWT.NONE);
		resetButton.setBounds(165, 604, 80, 30);
		resetButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				getShell().close();
			}
		});
		resetButton.setImage(SWTResourceManager.getImage(CourseAppMgm.class,
				"/img/Refresh.png"));
		resetButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		resetButton.setText("Reset");

		Button addProductButton = new Button(composite, SWT.NONE);
		addProductButton.setBounds(336, 604, 124, 30);
		addProductButton.setImage(SWTResourceManager.getImage(
				CourseAppMgm.class, "/img/Symbol-Add.png"));
		addProductButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Long id = (Long) getParams().get(CourseAppCtrl.COURSE_ID);

				params.put(AppConstant.APPCTRL, CourseAppCtrl.COURSE_CTRL);
				params.put(AppConstant.ACTION, CourseAppCtrl.COURSE_PRODENQ);
				params.put(CourseAppCtrl.COURSE_ID, id);
				shlUpdateCourse.close();
			}
		});
		addProductButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		addProductButton.setText("Add Product");

		Button delProductButton = new Button(composite, SWT.NONE);
		delProductButton.setBounds(466, 604, 149, 30);
		delProductButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		delProductButton.setImage(SWTResourceManager.getImage(
				CourseAppMgm.class, "/img/Symbol-Restricted.png"));
		delProductButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (!InventoryAppEnq.isProductInTransaction(table)) {
					int rowCount = doDeleteProduct(table);
					if (rowCount == 1) {
						populateTable(table, text, lblProducts);
					}
				} else {
					message(getShell(),
							"Delete Error.",
							"Unable to delete product. Product already used in transaction.",
							SWT.ICON_ERROR | SWT.OK);
				}
			}
		});
		delProductButton.setText("Delete Product");

		updateButton = new Button(composite, SWT.NONE);
		updateButton.setBounds(10, 604, 149, 30);
		updateButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				try {
					Course course = new CourseModel();

					Session session = HibernateUtil.getSessionFactory()
							.getCurrentSession();
					session.beginTransaction();

					course = (Course) setModel(composite, "course", course);
					course = (Course) session.get(CourseModel.class,
							course.getId());

					Double xquantity = course.getQuantity();

					course = (Course) setModel(composite, "course", course);
					CourseAppMgmRmk dialog = null;
					if (course.getQuantity().doubleValue() > xquantity
							.doubleValue()) {
						dialog = new CourseAppMgmRmk(getShell(),
								SWT.ICON_INFORMATION, getParams(), true);
					} else if (course.getQuantity().doubleValue() < xquantity
							.doubleValue()) {
						dialog = new CourseAppMgmRmk(getShell(),
								SWT.ICON_INFORMATION, getParams(), false);
					}
					if (dialog != null) {
						dialog.open();
					}

					log.debug(course.getClass().getSimpleName() + " : "
							+ course.getValues().toString());

					List<String> errors = CourseAppNew.validateForm(course);
					if (errors.isEmpty()) {
						course = (Course) preUpdate(course, getParams());
						Category category = null;

						if (combo.getText().length() > 0) {
							List<Category> categories = session
									.createCriteria(CategoryModel.class)
									.add(Expression.eq(Category.FLD_NAME,
											combo.getText()))
									.add(Expression.eq(Category.FLD_STATUS,
											AppConstant.STATUS_ACTIVE)).list();
							if (categories != null && !categories.isEmpty()) {
								category = categories.get(0);
							}

							if (category != null && category.getId() != null) {
								course.setCategory(category);
							}
						}

						int rowCount = doUpdate(course);
						if (rowCount == 1) {
							message(getShell(), "Update Success.",
									"Course updated successfully.");

							getParams().put(AppConstant.APPCTRL,
									CourseAppCtrl.COURSE_CTRL);
							getParams().put(AppConstant.ACTION,
									CourseAppCtrl.COURSE_ENQ);
							getShell().close();
						}
					} else {
						message(getShell(), "Update Error.", errors,
								SWT.ICON_ERROR | SWT.OK);
					}
				} catch (Exception ex) {
					message(getShell(), "Update Error.", ex.getMessage(),
							SWT.ICON_ERROR | SWT.OK);
					log.error("Unable to update course.", ex);
				}
			}
		});
		updateButton.setImage(SWTResourceManager.getImage(CourseAppMgm.class,
				"/img/Edit.png"));
		updateButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		updateButton.setText("Update Course");

		tableTreatment = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION);
		tableTreatment.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				TableItem[] items = tableTreatment.getSelection();
				if (items != null && items.length > 0) {
					for (int i = 0; i < items.length; i++) {
						TableItem item = items[i];
						if (item.getData() != null) {
							CourseTreatment courseTreatment = (CourseTreatment) item
									.getData();

							getParams().put(CourseAppCtrl.COURSETREAT_ID,
									courseTreatment.getId());
							getParams().put(CourseAppCtrl.COURSE_ID,
									courseTreatment.getCourse().getId());

							CourseTreatAppMgm dialog = new CourseTreatAppMgm(
									getShell(), SWT.ICON_INFORMATION,
									getParams());
							dialog.open();
						}
					}
				}
			}
		});
		tableTreatment.setLinesVisible(true);
		tableTreatment.setHeaderVisible(true);
		tableTreatment.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		tableTreatment.setBounds(10, 433, 1171, 145);

		TableColumn tableColumn = new TableColumn(tableTreatment, SWT.NONE);
		tableColumn.setWidth(100);
		tableColumn.setText("No.");

		TableColumn tableColumn_1 = new TableColumn(tableTreatment, SWT.NONE);
		tableColumn_1.setWidth(507);
		tableColumn_1.setText("Name");

		TableColumn tableColumn_2 = new TableColumn(tableTreatment, SWT.NONE);
		tableColumn_2.setWidth(314);
		tableColumn_2.setText("SKU");

		TableColumn tableColumn_3 = new TableColumn(tableTreatment, SWT.NONE);
		tableColumn_3.setWidth(100);
		tableColumn_3.setText("Price");

		TableColumn tableColumn_4 = new TableColumn(tableTreatment, SWT.NONE);
		tableColumn_4.setWidth(142);
		tableColumn_4.setText("Quanttiy");

		Button btnNewButton = new Button(composite, SWT.NONE);
		btnNewButton.setImage(SWTResourceManager.getImage(CourseAppMgm.class,
				"/img/Symbol-Add.png"));
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Long id = (Long) getParams().get(CourseAppCtrl.COURSE_ID);

				params.put(AppConstant.APPCTRL, CourseAppCtrl.COURSE_CTRL);
				params.put(AppConstant.ACTION, CourseAppCtrl.COURSE_TREATENQ);
				params.put(CourseAppCtrl.COURSE_ID, id);
				shlUpdateCourse.close();
			}
		});
		btnNewButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		btnNewButton.setBounds(671, 604, 143, 30);
		btnNewButton.setText("Add Treatment");

		Button btnDeleteTreatment = new Button(composite, SWT.NONE);
		btnDeleteTreatment.setImage(SWTResourceManager.getImage(
				CourseAppMgm.class, "/img/Edit.png"));
		btnDeleteTreatment.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int rowCount = doDeleteTreatment(tableTreatment);
				if (rowCount == 1) {
					populateTableTreatment(tableTreatment, text, lblTreatments);
				}

			}
		});
		btnDeleteTreatment.setText("Delete Treatment");
		btnDeleteTreatment.setFont(org.eclipse.wb.swt.SWTResourceManager
				.getFont("Segoe UI", 12, SWT.NORMAL));
		btnDeleteTreatment.setBounds(820, 604, 161, 30);

		composite.setTabList(new Control[] { combo, text, text_2, text_12,
				text_3, text_4, text_5, text_6, text_7, text_8, updateButton,
				resetButton });

		//
		buildStandardMenu(getShell(), getParams(), CourseAppCtrl.COURSE_CTRL,
				CourseAppCtrl.COURSE_ENQ);

		populateTable(table, text, lblProducts);
		populateTableTreatment(tableTreatment, text, lblTreatments);
	}

	private void populateControls(Composite composite, Combo combo) {
		if (getParams().get(CourseAppCtrl.COURSE_ID) == null) {
			getParams().put(InventoryAppCtrl.INVENTORY_MSG,
					"Unable to display product. Product ID not found.");

			getParams().put(AppConstant.APPCTRL,
					InventoryAppCtrl.INVENTORY_CTRL);
			getParams().put(AppConstant.ACTION, InventoryAppCtrl.INVENTORY_ENQ);
			getShell().close();
		}

		try {
			Long id = (Long) getParams().get(CourseAppCtrl.COURSE_ID);

			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();

			Course course = (Course) session.get(CourseModel.class, id);

			if (course != null && course.getId() != null) {
				setControls(composite, "course", course);

				List<Category> categories = session
						.createCriteria(CategoryModel.class)
						.add(Restrictions.eq(Category.FLD_TYPE,
								Category.TYPE_COURSE))
						.add(Restrictions.eq(Category.FLD_STATUS,
								AppConstant.STATUS_ACTIVE)).list();

				int index = 0;
				for (Iterator<Category> iter = categories.iterator(); iter
						.hasNext();) {
					Category category = iter.next();

					combo.add(category.getName());
					if (course.getCategory().getName()
							.equals(category.getName())) {
						combo.select(index);
					}
					index++;
				}
			}
		} catch (Exception e) {
			log.error("Unable to populate control.", e);
		}
	}

	private int doUpdate(Course course) throws Exception {
		int rowCount = 0;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();
			rowCount++;

			session.saveOrUpdate(course);
			log.debug(course.getClass().getSimpleName() + " : "
					+ course.getValues().toString());

			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			log.error("Unable to update product.", e);
			throw e;
		}

		return rowCount;
	}

	public Shell getShell() {
		return shlUpdateCourse;
	}

	public void populateTable(Table table, Text text, Label label) {
		StringBuffer sb = new StringBuffer();
		table.clearAll();
		table.removeAll();
		table.redraw();
		int count = 0;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();

			session.beginTransaction();
			// TODO Replace with StringUtills
			List<CourseProduct> courseProducts = new ArrayList<CourseProduct>();
			Long id = (Long) getParams().get(CourseAppCtrl.COURSE_ID);

			Criteria cris = session.createCriteria(CourseProductModel.class);

			Course course = (Course) session.get(CourseModel.class, id);
			if (course != null) {
				cris.add(Restrictions.eq(CourseProduct.FLD_COURSE, course));
			}
			cris.add(Restrictions.eq(CourseProduct.FLD_STATUS,
					AppConstant.STATUS_ACTIVE));

			courseProducts = cris.list();

			DecimalFormat df0 = new DecimalFormat();
			df0.applyPattern("##########.##");
			df0.setMinimumFractionDigits(0);
			df0.setMaximumFractionDigits(0);

			for (Iterator<CourseProduct> iter = courseProducts.iterator(); iter
					.hasNext();) {
				CourseProduct courseProduct = iter.next();
				count++;
				TableItem item = new TableItem(table, SWT.BORDER);
				Product product = courseProduct.getProduct();
				item.setText(new String[] { count + ".", product.getName(),
						product.getSku(), df0.format(product.getPrice()),
						Double.toString(courseProduct.getQuantity()) });
				item.setData(courseProduct);
			}
			sb.append(count).append(" product(s) found in this course.");
		} catch (Exception e) {
			sb.append("No result found. [").append(e.getMessage()).append("]");
			log.error(sb.toString(), e);
		}
		label.setText(sb.toString());
	}

	public void populateTableTreatment(Table table, Text text, Label label) {
		StringBuffer sb = new StringBuffer();
		table.clearAll();
		table.removeAll();
		table.redraw();
		int count = 0;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();

			session.beginTransaction();
			// TODO Replace with StringUtills
			List<CourseTreatment> courseTreatments = new ArrayList<CourseTreatment>();
			Long id = (Long) getParams().get(CourseAppCtrl.COURSE_ID);

			Criteria cris = session.createCriteria(CourseTreatmentModel.class);

			Course course = (Course) session.get(CourseModel.class, id);
			if (course != null) {
				cris.add(Restrictions.eq(CourseTreatment.FLD_COURSE, course));
			}
			cris.add(Restrictions.eq(CourseTreatment.FLD_STATUS,
					AppConstant.STATUS_ACTIVE));

			courseTreatments = cris.list();

			DecimalFormat df0 = new DecimalFormat();
			df0.applyPattern("##########.##");
			df0.setMinimumFractionDigits(0);
			df0.setMaximumFractionDigits(0);

			for (Iterator<CourseTreatment> iter = courseTreatments.iterator(); iter
					.hasNext();) {
				CourseTreatment courseTreatment = iter.next();
				count++;
				TableItem item = new TableItem(table, SWT.BORDER);
				Treatment treatment = courseTreatment.getTreatment();
				item.setText(new String[] { count + ".", treatment.getName(),
						treatment.getSku(), df0.format(treatment.getPrice()),
						Double.toString(courseTreatment.getQuantity()) });
				item.setData(courseTreatment);
			}
			sb.append(count).append(" treatment(s) found in this course.");
		} catch (Exception e) {
			sb.append("No result found. [").append(e.getMessage()).append("]");
			log.error(sb.toString(), e);
		}
		label.setText(sb.toString());
	}

	private int doDeleteProduct(Table table) {
		int rowCount = 0;
		try {
			TableItem[] items = table.getSelection();
			if (items != null && items.length > 0) {
				for (int i = 0; i < items.length; i++) {
					TableItem item = items[i];
					if (item.getData() != null) {
						CourseProduct courseProduct = (CourseProduct) item
								.getData();

						MessageBox box = new MessageBox(getShell(),
								SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
						box.setText("Confirm Delete Product?");
						box.setMessage("Are you sure you want to delete this product?");

						int reply = box.open();
						if (reply == SWT.OK) {
							Session session = HibernateUtil.getSessionFactory()
									.getCurrentSession();

							try {
								session.beginTransaction();

								courseProduct
										.setStatus(AppConstant.STATUS_OBSOLETE);
								courseProduct = (CourseProduct) preUpdate(
										courseProduct, getParams());

								session.update(courseProduct);
								rowCount++;

								// ProductAppNew.logProduct(product,
								// getParams(),
								// ProductLog.ACT_STOCK_OUT + "-"
								// + ProductLog.ACT_DELETE, null,
								// product.getQuantity());

								session.getTransaction().commit();
							} catch (Exception ex) {
								session.getTransaction().rollback();
								throw ex;
							}
						}
						break;
					}
				}
			}
		} catch (Exception e) {
			log.error("Unable to delete product.", e);
		}
		return rowCount;
	}

	private int doDeleteTreatment(Table table) {
		int rowCount = 0;
		try {
			TableItem[] items = table.getSelection();
			if (items != null && items.length > 0) {
				for (int i = 0; i < items.length; i++) {
					TableItem item = items[i];
					if (item.getData() != null) {
						CourseTreatment courseTreatment = (CourseTreatment) item
								.getData();

						MessageBox box = new MessageBox(getShell(),
								SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
						box.setText("Confirm Delete Treatment?");
						box.setMessage("Are you sure you want to delete this treatment?");

						int reply = box.open();
						if (reply == SWT.OK) {
							Session session = HibernateUtil.getSessionFactory()
									.getCurrentSession();

							try {
								session.beginTransaction();

								courseTreatment
										.setStatus(AppConstant.STATUS_OBSOLETE);
								courseTreatment = (CourseTreatment) preUpdate(
										courseTreatment, getParams());

								session.update(courseTreatment);
								rowCount++;

								// ProductAppNew.logProduct(product,
								// getParams(),
								// ProductLog.ACT_STOCK_OUT + "-"
								// + ProductLog.ACT_DELETE, null,
								// product.getQuantity());

								session.getTransaction().commit();
							} catch (Exception ex) {
								session.getTransaction().rollback();
								throw ex;
							}
						}
						break;
					}
				}
			}
		} catch (Exception e) {
			log.error("Unable to delete treatment.", e);
		}
		return rowCount;
	}
}
